package com.shuqi.activity.viewport;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.shuqi.activity.ActivityManager;
import com.shuqi.activity.BookContentActivity;
import com.shuqi.activity.BookCoverActivity;
import com.shuqi.activity.LoginActivity;
import com.shuqi.activity.PayActivity;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.Log4an;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookInfoDao;
import com.shuqi.database.model.BookInfo;
import com.shuqi.database.model.UserInfo;
import com.shuqi.model.bean.BuyBookInfo;
import com.shuqi.model.bean.ChapterInfo;
import com.shuqi.model.bean.OrderInfo;
import com.shuqi.model.manager.BuyBookManager;
import com.shuqi.model.manager.BuyBookManager.BuyChapterInfoInterface;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 价格变动订单提示
 * 
 * @author Jianda.Yang
 * 
 * @Date 2014-3-11 上午11:40:30
 */
public class PriceChangeDialog implements OnClickListener {
    private Activity mContext;
    private OrderInfo mOrderInfo;
    private View mView;
    private BottomDialog mBottomDialog;
    private TextView mCancelTextView, mBuyTextView;// 按钮
    private final int MSG_SUCCESS = 3;// 按章成功
    private final int MSG_BUY_BOOK_SUCCESS = 4;// 按本成功
    private final int MSG_RETURN_10 = 10;// 返回结果为10
    private final int MSG_ERROR = -1;
    private ChapterInfo mBookInfo;
    private TextView mTitleTextView, mToastTextView, mBuyStateTextView;
    private LinearLayout mButtonLayout, mLoadingLayout;
    private View mLineView;
    private ImageView mLoadImageView;
    private ProgressBar mProgressBar;

    public PriceChangeDialog(Activity context, OrderInfo orderInfo, onPriceListener mOnPriceListener) {
        this.mOnPriceListener = mOnPriceListener;
        mContext = context;
        mOrderInfo = orderInfo;
        mView = View.inflate(context, R.layout.view_price_change, null);
        mBottomDialog = new BottomDialog(mContext, mView);
        findID(mView);
        init();
    }

    private void findID(View view) {
        mTitleTextView = (TextView) view.findViewById(R.id.price_change_title_tv);
        mToastTextView = (TextView) view.findViewById(R.id.price_change_totast_tv);
        mLineView = (View) view.findViewById(R.id.price_change_line);
        mButtonLayout = (LinearLayout) view.findViewById(R.id.price_change_btn_lin);
        mLoadingLayout = (LinearLayout) view.findViewById(R.id.price_changet_buyLoading);
        mBuyStateTextView = (TextView) view.findViewById(R.id.price_changet_buy_states);
        mLoadImageView = (ImageView) view.findViewById(R.id.price_changet_buy_ok);
        mProgressBar = (ProgressBar) view.findViewById(R.id.price_changet_progressBar);
    }

    private void init() {
        mCancelTextView = (TextView) mView.findViewById(R.id.cancel_tv);
        mBuyTextView = (TextView) mView.findViewById(R.id.ok_tv);
        mCancelTextView.setOnClickListener(this);
        mBuyTextView.setOnClickListener(this);
        mToastTextView.setText("所购内容价格由" + mOnPriceListener.getOldPrice() + "书豆变为"
                + mOnPriceListener.getNewPrice() + "书豆,是否继续购买?");
    }

    private void showLoading() {
        mTitleTextView.setVisibility(View.GONE);
        mToastTextView.setVisibility(View.GONE);
        mLineView.setVisibility(View.GONE);
        mButtonLayout.setVisibility(View.GONE);
        mLoadingLayout.setVisibility(View.VISIBLE);
        mLoadImageView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.VISIBLE);
        mBuyStateTextView.setText(mContext.getResources().getString(
                R.string.bookcontent_order_loading));
    }

    private void goneLoadging() {
        mLoadingLayout.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.GONE);
        dismiss();
    }

    /** 购买成功提示 */
    public void showBuySuccessful() {
        mTitleTextView.setVisibility(View.GONE);
        mToastTextView.setVisibility(View.GONE);
        mLineView.setVisibility(View.GONE);
        mButtonLayout.setVisibility(View.GONE);
        if (mBookInfo != null && !TextUtils.isEmpty(mBookInfo.getMsg())) {
            if (mContext instanceof BookContentActivity) {
                if (mContext.isFinishing())
                    return;
            }
            BottomToast.makeToast(mContext, mBookInfo.getMsg(), R.drawable.common_icon_success)
                    .show();
        }
    }

    /** 购买成功提示 */
    public void showBuyBookSuccessful() {
        mTitleTextView.setVisibility(View.GONE);
        mToastTextView.setVisibility(View.GONE);
        mLineView.setVisibility(View.GONE);
        mButtonLayout.setVisibility(View.GONE);
        if (mBuyBookInfo != null && !TextUtils.isEmpty(mBuyBookInfo.getInfo())) {
            if (mContext instanceof BookContentActivity) {
                if (mContext.isFinishing())
                    return;
            }
            BottomToast.makeToast(mContext, mBuyBookInfo.getInfo(), R.drawable.common_icon_success)
                    .show();
        }
    }

    private onPriceListener mOnPriceListener;

    public interface onPriceListener {
        public String getOldPrice();

        public String getNewPrice();
    }

    /** 显示订单对话框 */
    public void show() {
        if (mBottomDialog != null && !mBottomDialog.isShowing()) {
            mBottomDialog.show();
        }
    }

    private void dismiss() {
        if (mBottomDialog != null && mBottomDialog.isShowing()) {
            mBottomDialog.dismiss();
        }
    }

    private int getAutoBuyState(String bid, String uid) {
        if (TextUtils.isEmpty(bid)|| TextUtils.isEmpty(uid)) {
            return -1;
        }
        BookInfo bookInfo = BookInfoDao.getInstance().getBookInfo(null, bid, uid);
        return bookInfo.getBookAutoBuyState();
    }

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_SUCCESS:
                    if (mContext instanceof BookContentActivity) {
                        int state =
                                getAutoBuyState(mBookInfo.getBookId(), MyAccountManager
                                        .getInstance(mContext).getUserId());
                        Log4an.i("yjd", "1.【PriceChangeDialog】state="+state);
                        if (state == BookInfo.DEFAULT_NO_AUTO_BUY) {
                            BookInfoDao.getInstance().updateAutoBuyBookState(mBookInfo.getBookId(),
                                    null, MyAccountManager.getInstance(mContext).getUserId(),
                                    BookInfo.AUTO_BUY);
                        } else if (state == BookInfo.NO_AUTO_BUY) {
                            BookInfoDao.getInstance().updateAutoBuyBookState(mBookInfo.getBookId(),
                                    null, MyAccountManager.getInstance(mContext).getUserId(),
                                    BookInfo.NO_AUTO_BUY);
                        }
                        else if (state == BookInfo.AUTO_BUY) {
                            BookInfoDao.getInstance().updateAutoBuyBookState(mBookInfo.getBookId(),
                                    null, MyAccountManager.getInstance(mContext).getUserId(),
                                    BookInfo.AUTO_BUY);
                        }
                        goneLoadging();
                        ((BookContentActivity) mContext).mBookContentModel.refreshPage(mBookInfo,
                                false);
                        showBuySuccessful();
                    }
                    break;
                case MSG_BUY_BOOK_SUCCESS:
                    goneLoadging();
                    if (mContext instanceof BookContentActivity) {
                        ((BookContentActivity) mContext).mBookContentModel.refreshDownView();
                        showBuyBookSuccessful();
                    } else if (mContext instanceof BookCoverActivity) {
                        String s = null;
                        if (mBuyBookInfo != null) {
                            s=TextUtils.isEmpty(mBuyBookInfo.getInfo())?null:mBuyBookInfo.getInfo();
                        }
                        ((BookCoverActivity) mContext).loadCoverData(s);
                    }
                    break;
                case MSG_RETURN_10:
                    LoginActivity.openVerifyForResult(mContext, LoginActivity.LOGINTYPE_VERIFY);
                    break;
                case MSG_ERROR:
                    String s = "购买失败";
                    if (mBookInfo != null && !TextUtils.isEmpty(mBookInfo.getMsg())) {
                        s = mBookInfo.getMsg();
                    }
                    if (mBuyBookInfo != null && !TextUtils.isEmpty(mBuyBookInfo.getInfo())) {
                        s = mBuyBookInfo.getInfo();
                    }
                    showBuyFailed(s);
                    if(mBookInfo==null)
                        return;
                    int state =
                            getAutoBuyState(mBookInfo.getBookId(),
                                    MyAccountManager.getInstance(mContext).getUserId());
                    Log4an.i("yjd", "2.【PriceChangeDialog】state="+state);
                    if (state == BookInfo.DEFAULT_NO_AUTO_BUY) {
                        BookInfoDao.getInstance().updateAutoBuyBookState(mBookInfo.getBookId(),
                                null, MyAccountManager.getInstance(mContext).getUserId(),
                                BookInfo.AUTO_BUY);
                    } else if (state == BookInfo.NO_AUTO_BUY) {
                        BookInfoDao.getInstance().updateAutoBuyBookState(mBookInfo.getBookId(),
                                null, MyAccountManager.getInstance(mContext).getUserId(),
                                BookInfo.NO_AUTO_BUY);
                    }
                    break;
            }
        };
    };

    public void showBuyFailed(String failureMessage) {
        dismiss();
        if (mContext instanceof BookContentActivity) {
            if (mContext.isFinishing())
                return;
        }
        BottomToast.makeToast(mContext, failureMessage, R.drawable.common_icon_fail).show();
    }

    private void buyChapter() {

        Log4an.e("yjd",
                "【按章价格变动继续购买】bid=" + mOrderInfo.getBookId() + ",cid=" + mOrderInfo.getChapterId()
                        + ",uid=" + MyAccountManager.getInstance(mContext).getUserId()
                        + ",new Price=" + mOnPriceListener.getNewPrice());
        showLoading();
        StatisticsUtils.onEvent(mContext, StatisticsEventID.BOOKCONTENT_CLICK_BUY_CHAPTER);
        try {
            BuyBookManager.buyChapterOnline(mContext, mOrderInfo.getBookId(),
                    mOrderInfo.getChapterId(), MyAccountManager.getInstance(mContext).getUserId(),
                    new BuyChapterInfoInterface() {

                        @Override
                        public void onFinish(ChapterInfo info) {

                            Log.e("yjd", "返回状态：" + info.getCurChapterType());
                            Log.e("yjd",
                                    "[返回]bid=" + info.getBookId() + ",update="
                                            + info.getIsUpdateCatalog() + ",price="
                                            + info.getCurChapterPrice() + ",msg=" + info.getMsg());
                            if ("1".equals(info.getCurChapterType())) {
                                mBookInfo = info;
                                handler.sendEmptyMessage(MSG_SUCCESS);
                            } else if ("10".equals(info.getCurChapterType())) {
                                handler.sendEmptyMessage(MSG_RETURN_10);

                            } else {
                                mBookInfo = info;
                                handler.sendEmptyMessage(MSG_ERROR);
                            }
                        }
                    }, mOnPriceListener.getNewPrice());
        } catch (Exception e) {
            e.printStackTrace();
            // handler.sendEmptyMessage(buy_successful);
            // if (mOrderInfo != null && !TextUtils.isEmpty(mOrderInfo.getBookId())) {
            // Toast.makeText(mContext, "帐号是8000000，不能购买", Toast.LENGTH_LONG).show();
            // }
            return;
        }


    }

    private final String RETURN_OK = "1";
    private final String RETURN_NO_LOGIN = "10";
    private final int MSG_BUYALLBOOK_FAILURE = 11;// 购买全本失败
    private BuyBookInfo mBuyBookInfo;

    private void buyBook() {
        StatisticsUtils.onEvent(mContext, StatisticsEventID.BOOKCONTENT_CLICK_BUY_BOOK);
        showLoading();
        Log4an.e("yjd",
                "【全本价格变动继续购买】bid=" + mOrderInfo.getBookId() + ",cid=" + mOrderInfo.getChapterId()
                        + ",uid=" + MyAccountManager.getInstance(mContext).getUserId()
                        + ",new Price=" + mOnPriceListener.getNewPrice());
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                try {
                    BuyBookInfo buyBookInfo =
                            BuyBookManager.buyBookOnline(mContext, mOrderInfo.getBookId(),
                                    mOrderInfo.getChapterId(),
                                    MyAccountManager.getInstance(mContext).getUserId(),
                                    mOnPriceListener.getNewPrice()); // 打开即为请求购买全本
                    Log4an.e("yjd", "【全本购买】getType=" + buyBookInfo.getType());
                    Log.e("yjd",
                            "[返回]bid=" + buyBookInfo.getBookId() + ",update="
                                    + buyBookInfo.getIsUpdateCatalog() + ",price="
                                    + buyBookInfo.getCurChapterPrice() + ",msg=" + buyBookInfo.getInfo());
                    if (RETURN_OK.equals(buyBookInfo.getType())) {
                        mBuyBookInfo = buyBookInfo;
                        handler.sendEmptyMessage(MSG_BUY_BOOK_SUCCESS);
                    } else if (RETURN_NO_LOGIN.equals(buyBookInfo.getType())) {
                        handler.sendEmptyMessage(MSG_RETURN_10);
                        Message msg = new Message();
                        msg.what = MSG_BUYALLBOOK_FAILURE;
                        if (buyBookInfo != null) {
                            msg.obj = buyBookInfo.getInfo();
                        }
                        handler.sendMessage(msg);
                    } else {
                        mBuyBookInfo = buyBookInfo;
                        handler.sendEmptyMessage(MSG_ERROR);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }

            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel_tv:
                dismiss();
                break;
            case R.id.ok_tv:
                UserInfo userInfo = MyAccountManager.getInstance(ShuqiApplication.getContext());
                Log4an.e("yjd", "【价格变动】getPrice=" + mOrderInfo.getPrice() + ",getBalance="
                        + userInfo.getBalance());
                Log4an.e("yjd", "【价格变动】余额充足：" + isBalanceEnough(userInfo.getBalance()));
                if (isBalanceEnough(userInfo.getBalance())) {
                    if (mOrderInfo != null) {
                        if (mOrderInfo.getPayMode() == 1) {
                            buyBook();
                        } else {
                            buyChapter();
                        }
                        StatisticsUtils.onEvent(mContext, StatisticsEventID.BOOKCONTENT_PRICE_BUY);
                    } else {
                        Intent intent = new Intent(mContext, PayActivity.class);
                        ActivityManager.getInstance().startNextActivityForResult(intent,
                                Activity.RESULT_CANCELED, mContext);
                        dismiss();
                    }
                    break;
                }
        }
    }

    /** 当前余额购买此内容是否充足 */
    private boolean isBalanceEnough(String userBalance) {
        if (mOrderInfo != null) {
            try {
                float price = Float.valueOf(mOrderInfo.getPrice());
                float balance =
                        TextUtils.isEmpty(userBalance) ? 0 : Float.valueOf(userBalance);
                return price <= balance;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }


}
